using static AnalyStock.DataManage.HttpClientUtility;

namespace AnalyStock.DataManage;

/// <summary>
///     封装对Tu Share API的调用
/// </summary>
public static class UtilityOfTuShare
{
    private static readonly Uri baseUrl = new("http://api.tushare.pro");

    /// <summary>
    ///     调用TuShare API
    /// </summary>
    /// <param name="apiName"></param>
    /// <param name="parmaMap"></param>
    /// <param name="fields"></param>
    /// <returns></returns>
    public static async Task<DataTable> GetTradeDataAsync(string apiName, Dictionary<string, string> parmaMap,
        string fields = default)
    {
        //设置适应国标GB213码，防止部分数据源显示乱码           
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        var tuShareParamObj = new TuShareParamObj { ApiName = apiName, Params = parmaMap, Fields = fields };
        //做Http调用
        var taskResults = await HttpClientPostAsync(baseUrl, tuShareParamObj).ConfigureAwait(false);
        var desResults = JsonSerializer.Deserialize<TuShareResult>(taskResults);
        //如果调用失败，抛出异常
        if (!string.IsNullOrWhiteSpace(desResults.Msg))
        {
            throw new Exception(desResults.Msg);
        }
        return desResults.ConvertToDaTaTable();
    }

    /// <summary>
    ///     转换为DaTaTable数据格式。返回结果分成两部分，一部分是列头信息，另一部分是数据本身。
    /// </summary>
    /// <param name="results"></param>
    /// <returns></returns>
    private static DataTable ConvertToDaTaTable(this TuShareResult results)
    {
        var dtResult = new DataTable();
        results.Data.Fields.ForEach(n => dtResult.Columns.Add(n));        
        results.Data.Items.ForEach(n => dtResult.Rows.Add(n));
        return dtResult;
    }


    private class TuShareParamObj
    {
        [JsonPropertyName("api_name")] public string ApiName { get; set; }

        [JsonPropertyName("token")]    public string Token { get; } 
                                            =ApplicationParam.TushareToken;//Token 
        [JsonPropertyName("params")] public Dictionary<string, string> Params { get; set; }

        [JsonPropertyName("fields")] public string Fields { get; set; }
    }

    private class TuShareResult
    {
        [JsonPropertyName("code")] public object Code { get; set; }

        [JsonPropertyName("msg")] public string Msg { get; set; }

        [JsonPropertyName("data")] public TuShareData Data { get; set; }
    }

    private class TuShareData
    {
        [JsonPropertyName("fields")] public string[] Fields { get; set; }

        [JsonPropertyName("items")] public object[][] Items { get; set; }
    }
}